import { stringify } from "querystring";
import type { Reducer, Effect } from "umi";
import { history } from "umi";

import { accountLogin } from "@/services/login";
import { setAuthority } from "@/utils/authority";
import { getPageQuery } from "@/utils/utils";

export type StateType = {
	status?: "ok" | "error";
	type?: string;
	currentAuthority?: "user" | "guest" | "admin";
};

export type LoginModelType = {
	namespace: string;
	state: StateType;
	effects: {
		login: Effect;
		logout: Effect;
	};
	reducers: {
		changeLoginStatus: Reducer<StateType>;
	};
};

const Model: LoginModelType = {
	namespace: "login",

	state: {
		status: undefined,
	},

	effects: {
		*login({ payload }, { call, put }) {
			const response = yield call(accountLogin, { ...payload });

			console.log(response, "response");
			if (response.code === 200) {
				yield put({
					type: "updateState",
					payload: { isLoading: true, status: "ok", currentAuthority: "admin" },
				});
				sessionStorage.setItem("access_token", response.data?.token);
				sessionStorage.setItem("nickName", response.data.userRealName || "");
				history.replace("/");
			}
		},

		*logout({ payload }, { call, put }) {
			const { redirect } = getPageQuery();
			if (window.location.pathname !== "/user/login" && !redirect) {
				sessionStorage.setItem("access_token", "");
				sessionStorage.setItem("nickName", "");
				yield put({
					type: "updateState",
					payload: { status: "error", currentAuthority: "guest" },
				});
				history.replace({
					pathname: "/user/login",
					search: stringify({
						redirect: window.location.href,
					}),
				});
			}
		},
	},

	reducers: {
		changeLoginStatus(state, { payload }) {
			setAuthority(payload.currentAuthority);
			return {
				...state,
				status: payload.status,
				type: payload.type,
			};
		},
	},
};

export default Model;
